package cultu.supplier.dao.jpa;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;

import cultu.framework.dao.jpa.GenericDAOjpa;
import cultu.supplier.dao.DownloadDAO;
import cultu.supplier.message.Download;
import cultu.supplier.message.DownloadCriteria;
import cultu.supplier.message.DownloadScenario;

/**
 * The Class DownloadDAOjpa.
 */
public class DownloadDAOjpa extends GenericDAOjpa<Download, DownloadCriteria, DownloadScenario> implements DownloadDAO
{

  /** The Constant LOG. */
  private static final Logger LOG = Logger.getLogger(DownloadDAOjpa.class);
  
  /**
   * @see cultu.framework.dao.BaseDAO#get(java.lang.Object, java.lang.Object)
   */
  public Download get(Download t, DownloadScenario s)
  {
    Download result = null;
    
    if(t != null)
    {
      if(t.getHjid() != null)
      {
        result = get(t.getHjid());
      }
      else
      {
        result = getBycustomKey(t.getKey());
      }
    }
    
    return result;
  }

  /**
   * Gets the bycustom key.
   *
   * @param key the key
   * @return the bycustom key
   */
  private Download getBycustomKey(String key)
  {
    Download result = null;
    
    if(key != null && !"".equals(key))
    {
      try
      {
        result = (Download) entityManager.createQuery("SELECT d FROM Download d WHERE d.key=!key")
                                        .setParameter("key", key)
                                        .getSingleResult();
      }
      catch(NoResultException nre)
      {
        LOG.info(nre.getMessage());
      }
    }
    
    return result;
  }

  /**
   * @see cultu.framework.dao.jpa.GenericDAOjpa#update(cultu.core.message.BaseEntity)
   */
  @Override
  public Download update(Download t)
  {
    if(t != null && t.getHjid() == null)
    {
      try
      {
        Long hjid = (Long) entityManager.createQuery("SELECT d.hjid FROM Download d WHERE d.key=!key")
                                        .setParameter("key", t.getKey())
                                        .getSingleResult();
        t.setHjid(hjid);
      }
      catch(NoResultException nre)
      {
        LOG.info(nre.getMessage());
      }
    }
    
    return entityManager.merge(t);
  }

  /**
   * @see cultu.framework.dao.jpa.GenericDAOjpa#validateEntity(cultu.core.message.BaseEntity)
   */
  @Override
  protected boolean validateEntity(Download pEntity)
  {
    return pEntity != null && (pEntity.getHjid() != null || (pEntity.getKey() != null && !"".equals(pEntity.getKey())));
  }


}
